package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Focus;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class FocusApiImpl implements FocusApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long userFocusId) {
        //1、保存自己的关注数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("focusId").is(userFocusId));
        //1.1 判断关注关系是否存在
        if (!mongoTemplate.exists(query, Focus.class)) {
            //1.2 如果不存在，保存
            Focus focus = new Focus();
            focus.setUserId(userId);
            focus.setFocusId(userFocusId);
            focus.setCreated(System.currentTimeMillis());
            mongoTemplate.save(focus);
        }
    }

    @Override
    public void delete(Focus focus) {
        mongoTemplate.remove(focus);
    }


    /*
     * 查看是否关注
     * */
    @Override
    public Boolean findRelationship(Long userId, Long userFocusId) {
        //1、保存自己的关注数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("focusId").is(userFocusId));
        //1.1 判断关注关系是否存在
        Focus userFocus = mongoTemplate.findOne(query, Focus.class);
        if (userFocus != null) {
            return true;
        }
        return false;
    }

    @Override
    public Focus findFocus(Long userId, Long userUnFocusId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("focusId").is(userUnFocusId));
        return mongoTemplate.findOne(query, Focus.class);
    }
}
